package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;
import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public List<User> findAll() {
        System.out.println(userMapper.findAll());
        return userMapper.findAll();
    }
    //登录
    @Override
    public User findUser(String username, String password) {
        return userMapper.findUser(username, PasswordUtil.md5(password));
    }
    @Override
    public List<User> findNickname(String nickname) {
        return userMapper.findNickname(nickname);
    }
    @Override
    public boolean register(User user) {
        user.setPassword(PasswordUtil.md5(user.getPassword()));
        if(userMapper.addUser(user)>0){
            //密码加密
            user.setPassword(PasswordUtil.md5(user.getPassword()));
            return true;
        }
        return true;
    }
    //  查询邮箱号是否存在
    @Override
    public int findUserByEmail(String email) {
        return userMapper.findUserByEmail( email);
    }
    @Override
    public int updateUser(String email,String password) {
        //密码加密
        // 如果验证码正确=》修改密码
        return userMapper.updateUser(email, PasswordUtil.md5(password));
    }
    @Override
    public void sendEmail(String email) {
        // 生成验证码
        String code =  emailService.generateCode();
//           把生成的验证码存储到redist数据库中
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
//       存储验证码code到redis中
        ops.set(email, code,10, TimeUnit.MINUTES);// 存储10分钟
//      把验证码发送给邮箱
        emailService.sendEmail(email,code);
    }
    @Override
    public boolean findEmail(String email, String code) {
        // 判断输入的验证码是否正确：从redis数据库中提取出来进行判断
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(email);
//        判断验证码是否正确，验证码正确返回true，验证码错误返回false
        return redisCode != null &&  redisCode.equals(code);
    }








}
